package com.kuanter.kuanterauto.main;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.kuanter.kuanterauto.R;
import com.kuanter.kuanterauto.activity.CityListActivity;
import com.kuanter.kuanterauto.baseui.BaseActivity_NoBar;
import com.kuanter.kuanterauto.baseui.ProApplication;
import com.kuanter.kuanterauto.constants.HttpConfigAPI;
import com.kuanter.kuanterauto.constants.MainConstants;
import com.kuanter.kuanterauto.dataservices.PushServices;
import com.kuanter.kuanterauto.entity.KuanterService;
import com.kuanter.kuanterauto.entity.MapResult;
import com.kuanter.kuanterauto.entity.MessageInfo;
import com.kuanter.kuanterauto.net.HttpTask;
import com.kuanter.kuanterauto.net.HttpUtil;
import com.kuanter.kuanterauto.utils.DataLoader;
import com.kuanter.kuanterauto.utils.JsonParser;
import com.kuanter.kuanterauto.utils.SharePrefenceUtil;
import com.kuanter.kuanterauto.utils.StringUtils;
import com.umeng.analytics.MobclickAgent;

/**
 * main界面
 * 
 * @author soup
 * 
 */
@SuppressLint("HandlerLeak")
public class MainActivity extends BaseActivity_NoBar implements Runnable {

	int count = 0;

	Thread thread = null;

	public static int ID;

	// List<CardInfo> carinfos;
	// List<Consumption> consumptions;
	// List<VehicleInfo> vehicleInfos;
	public static boolean isPush = false;
	public static String DEVICEID = "";
	public static String SERIAL = "unknown";
	MapResult mapR = null;

	String version = "";
	String appName = "";
	String packageName = "";
	public static String Token = "";

	PackageManager packageManager = null;
	PackageInfo packInfo = null;
	private List<MessageInfo> messageInfos = null;

	public static int localVersion = 0;// 本地安装版本
	public static int serverVersion = 0;// 服务器版版本	
	String versionInfo = "";
	
	boolean check = false;  //是否已经检查更新
	
	Handler h = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if(msg.what == HttpTask.RESULT_OK) {
				String json = (String) msg.obj;
				List<KuanterService> list_kuanterService = JsonParser.getKuanterService(json);
				application.setList_kuanterService(list_kuanterService);
				finishProgress();
			}
			super.handleMessage(msg);
		}
		
	};
	
	ProApplication application;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		application = (ProApplication) getApplication();
		
		// 首先请求数据,得到服务列表和服务类型列表  TODO
		String cityID = SharePrefenceUtil.getCityID(this);
		if(!cityID.equals("")) {
			DataLoader loader = new DataLoader(this);
			List<NameValuePair> params1 = new ArrayList<NameValuePair>();
			NameValuePair citycode = new BasicNameValuePair("cityCode",cityID);
			params1.add(citycode);
			loader.DisplayData(
					MainConstants.HOST_test + HttpConfigAPI.FINDSERVICE, params1,
					h, "", false);
		}
		

	}

	// 获取本地id数据
	private void init() throws Exception {
		SharedPreferences sp = getSharedPreferences("userinfo", MODE_PRIVATE);
		String uId = sp.getString("id", "");
		if(!uId.equals("")) {
			ID = Integer.parseInt(uId);
		}
//		ID = sp.getInt("id", 0);

		// TelephonyManager tm = (TelephonyManager)
		// getSystemService(Context.TELEPHONY_SERVICE);
		// String
		// android_id=Settings.Secure.getString(getContentResolver(),Settings.Secure.ANDROID_ID);
		// DEVICEID = tm.getDeviceId();
		// try {
		// Class<?> clazz = Class.forName("android.os.SystemProperties");
		// Method method =clazz.getMethod("get", String.class);
		// SERIAL = (String) method.invoke(clazz, "ro.serialno");
		// } catch (Exception e) {
		// e.printStackTrace();
		// }

		// packageManager = getPackageManager();
		// packInfo = packageManager.getPackageInfo(getPackageName(),0);
		//
		// version=getVersionName();
		// appName=packInfo.applicationInfo.loadLabel(packageManager).toString();
		// packageName=packInfo.applicationInfo.packageName;

		clearNotification();

	}

	@Override
	protected void onResume() {
		if(!check) {
			
		if (PushServices.getmessageInfos() != null) {
			messageInfos = PushServices.getmessageInfos();
		}

		mapR = MapResult.getMapResults();
		// if (getIntent().getAction().equals(MainConstants.PUSH_ACTION)) {
		SharedPreferences sp = getSharedPreferences("push", MODE_PRIVATE);
		isPush = sp.getBoolean("push", false);
		// }

		final TelephonyManager tm = (TelephonyManager) getBaseContext()
				.getSystemService(Context.TELEPHONY_SERVICE);
		final String tmDevice, tmSerial, androidId;
		tmDevice = "" + tm.getDeviceId();
		tmSerial = "" + tm.getSimSerialNumber();
		androidId = ""
				+ android.provider.Settings.Secure.getString(
						getContentResolver(),
						android.provider.Settings.Secure.ANDROID_ID);
		UUID deviceUuid = new UUID(androidId.hashCode(),
				((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
		Token = deviceUuid.toString();

//		stopServices();  TODO

		try {
			init();
		} catch (Exception e) {
			e.printStackTrace();
		}

//		getVersion();
		new Thread(checkVersionRun).start();
		
		MobclickAgent.onResume(this);
		
		check = true;
		} else {
			if(CheckNetworkState()) {
				handler.sendEmptyMessage(1);
			}
		}
		super.onResume();
	}

	@Override
	protected void onPause() {
		MobclickAgent.onPause(this);
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	private void stopServices() {
		PushServices.isRun = false;
		Intent i = new Intent(this, PushServices.class);
		stopService(i);
	}

	// private void LoadGRZXData(int id) throws Exception {
	// // 请求客户卡片数据
	// List<NameValuePair> params1 = new ArrayList<NameValuePair>();
	// params1.add(new BasicNameValuePair("cardInfo.userId", id + ""));
	// String result_cardInfo = HttpUtil.requestStringForPost(
	// MainConstants.HOST + "cardInfo/query_card", params1,this);
	// CardInfoList cardInfoList = new CardInfoList(result_cardInfo);
	// carinfos = cardInfoList.getCarinfos();
	// // 消费记录
	// List<NameValuePair> params2 = new ArrayList<NameValuePair>();
	// params2.add(new BasicNameValuePair("userConsumption.userId", id + ""));
	// String consumption = HttpUtil.requestStringForPost(MainConstants.HOST
	// + "consumption/query_consumption_record", params2,this);
	// ConsumptionList consumptionList = new ConsumptionList(consumption);
	// consumptions = consumptionList.getConsumptionList();
	//
	// // 车险数据
	// List<NameValuePair> params3 = new ArrayList<NameValuePair>();
	// params3.add(new BasicNameValuePair("vehicleInfo.userId", id + ""));
	// String vehicleInfo = HttpUtil.requestStringForPost(MainConstants.HOST
	// + "vehicleInfo/query_vehicle", params3,this);
	// // System.out.println(vehicleInfo);
	// VehicleInfoList vehicleInfoList = new VehicleInfoList(vehicleInfo);
	// vehicleInfos = vehicleInfoList.getVehicleInfoList();
	//
	// }

	/**
	 * 
	 * 获取当前程序的版本号 �??
	 */
	// private String getVersionName() throws Exception
	// {
	// String version = packInfo.versionName;
	// return version;
	// }

	@Override
	public void run() {
		while (true) {
			count++;

			try {
				Thread.sleep(1 * 1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

			if (count == 1) {
				Message msg = new Message();
				msg.what = 1;
				handler.sendMessage(msg);
			}
		}
	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == 1) {
				String city = SharePrefenceUtil.getCity(MainActivity.this);
//				Bundle city_bundle = new Bundle();
//				city_bundle.putString("city", city);
				//首先判断当前城市有没有选择，没选择就跳转到城市列表
				if(city.equals("")) {
					qStartActivity(CityListActivity.class, null);
					finish();
					startActivity_anim(0);
				} else {
					if (ID != 0) {
						// try {
						// LoadGRZXData(ID);
						// } catch (Exception e) {
						// e.printStackTrace();
						// }
						// if (carinfos != null && consumptions != null) {
						// Bundle b = new Bundle();
						// b.putSerializable(CardInfoList.TAG,
						// (Serializable) carinfos);
						// b.putSerializable(ConsumptionList.TAG,
						// (Serializable) consumptions);
						// b.putSerializable(VehicleInfoList.TAG,
						// (Serializable) vehicleInfos);
						// qStartActivity(HomeActivityGroup.class, b);
						// finish();
						// startActivity_anim(0);
						//
						// } else {
						if (messageInfos != null) {
							Bundle bundle = new Bundle();
							bundle.putSerializable(MessageInfo.TAG,
									(Serializable) messageInfos);
							qStartActivity(HomeActivityGroup.class, bundle);
							finish();
							startActivity_anim(0);
						} else {
							qStartActivity(HomeActivityGroup.class, null);
							finish();
							startActivity_anim(0);
						}
						// }
					} else {
						if (messageInfos != null) {
							Bundle bundle = new Bundle();
							bundle.putSerializable(MessageInfo.TAG,
									(Serializable) messageInfos);
							qStartActivity(HomeActivityGroup.class, bundle);
							finish();
							startActivity_anim(0);
						} else {
							qStartActivity(HomeActivityGroup.class, null);
							finish();
							startActivity_anim(0);
						}
					}
				}
				
			} else if(msg.what == 201) {
				checkVersion();
			} else if(msg.what == 300) {
				if(CheckNetworkState()) {
					new Thread(run_getVersion).start();
				}
			}
		}
	};
	
	Runnable run_getVersion = new Runnable() {
		
		@Override
		public void run() {
			// loader.DisplayData(MainConstants.HOST + "shopInfo/query_version",
			// null, mHandler,null,false);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("deviceToken", MainActivity.Token));
//			 dataLoader.DisplayData(MainConstants.HOST_test + "checkVersion",
//			 params, handler,"",false);
			String result = HttpUtil.requestStringForPost(MainConstants.HOST_test
					+ "checkVersion", params);

			try {
				if (!result.equals("网络连接错误")) {
					if (StringUtils.isSuccess(result)) {
						JSONObject jobj = new JSONObject(result);
						JSONObject jo = jobj.optJSONObject("curVersion");
						serverVersion = Integer.parseInt(jo
								.optString("versionId"));
						versionInfo = jo.optString("versionInfo");
//						checkVersion();
						handler.sendEmptyMessage(201);
					} else {
						/*if (thread == null) {
							thread = new Thread(this);
							thread.start();
						}*/
						handler.sendEmptyMessage(1);
					}
				} else {
					/*if (thread == null) {
						thread = new Thread(this);
						thread.start();
					}*/
					handler.sendEmptyMessage(1);
				}
			} catch (JSONException e) {
				/*if (thread == null) {
					thread = new Thread(this);
					thread.start();
				}*/
				handler.sendEmptyMessage(1);
				e.printStackTrace();

			}
		}
	};

	// 删除通知
	private void clearNotification() {
		// 启动后删除之前我们定义的通知
		NotificationManager notificationManager = (NotificationManager) this
				.getSystemService(NOTIFICATION_SERVICE);
		notificationManager.cancel(0);

	}
	
	Runnable checkVersionRun = new Runnable() {
		
		@Override
		public void run() {
			getVersion();
		}
	};

	public void getVersion() {
		// 版本更新
		try {
			PackageInfo packageInfo = getApplicationContext()
					.getPackageManager().getPackageInfo(getPackageName(), 0);
			localVersion = packageInfo.versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		/***
		 * 在这里写�?��方法用于请求获取服务器端的serverVersion.
		 */
		
		handler.sendEmptyMessage(300);
		
		/*if (CheckNetworkState()) {
			// loader.DisplayData(MainConstants.HOST + "shopInfo/query_version",
			// null, mHandler,null,false);
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("deviceToken", MainActivity.Token));
			// dataLoader.DisplayData(MainConstants.HOST + "checkVersion",
			// params, handler,"",false)1;
			String result = HttpUtil.requestStringForPost(MainConstants.HOST
					+ "checkVersion", params);

			try {
				if (!result.equals("网络连接错误")) {
					if (StringUtils.isSuccess(result)) {
						JSONObject jobj = new JSONObject(result);
						JSONObject jo = jobj.optJSONObject("curVersion");
						serverVersion = Integer.parseInt(jo
								.optString("versionId"));
						versionInfo = jo.optString("versionInfo");
//						checkVersion();
						handler.sendEmptyMessage(201);
					} else {
						if (thread == null) {
							thread = new Thread(this);
							thread.start();
						}
					}
				} else {
					if (thread == null) {
						thread = new Thread(this);
						thread.start();
					}
				}
			} catch (JSONException e) {
				if (thread == null) {
					thread = new Thread(this);
					thread.start();
				}
				e.printStackTrace();

			}
		}*/
	}

	/***
	 * �?��是否更新版本
	 */
	public void checkVersion() {
		if (localVersion < serverVersion) {
			// 发现新版本，提示用户更新
			AlertDialog.Builder builder = new AlertDialog.Builder(
					MainActivity.this);
			View v = LayoutInflater.from(MainActivity.this).inflate(
					R.layout.versionifon, null);
			TextView tv = (TextView) v.findViewById(R.id.tv_version);
			tv.setText(versionInfo);
			builder.setTitle("软件升级");
			builder.setMessage("发现新版本,建议立即更新使用.");
			builder.setView(v);

			builder.setPositiveButton("更新",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							Intent updateIntent = new Intent(MainActivity.this,
									UpdateService.class);
							updateIntent.putExtra("app_name", getResources()
									.getString(R.string.app_name));
							MainActivity.this.startService(updateIntent);
							dialog.dismiss();
//							handler.sendEmptyMessage(1);  //放在ondismisslistener里面
							/*if (messageInfos != null) {
								System.out.println("msg......");
								Bundle bundle = new Bundle();
								bundle.putSerializable(MessageInfo.TAG,
										(Serializable) messageInfos);
								qStartActivity(HomeActivityGroup.class, bundle);
								finish();
								startActivity_anim(0);
							} else {
								qStartActivity(HomeActivityGroup.class, null);
								finish();
								startActivity_anim(0);
							}*/
						}
					}).setNegativeButton("取消",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
//							handler.sendEmptyMessage(1);  
							/*if (messageInfos != null) {
								System.out.println("msg......");
								Bundle bundle = new Bundle();
								bundle.putSerializable(MessageInfo.TAG,
										(Serializable) messageInfos);
								qStartActivity(HomeActivityGroup.class, bundle);
								finish();
								startActivity_anim(0);
							} else {
								qStartActivity(HomeActivityGroup.class, null);
								finish();
								startActivity_anim(0);
							}*/
						}
					});
			AlertDialog dialog = builder.create();
			dialog.show();
			dialog.setOnDismissListener(new OnDismissListener() {
				@Override
				public void onDismiss(DialogInterface dialog) {
					handler.sendEmptyMessage(1);
				}
			});
//			builder.create().show();
		} else {
			if (thread == null) {
				thread = new Thread(this);
				thread.start();
			}
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

	}

}
